package com.linkage.jz.bankruptcy.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.CreateProjectDetailActivity;
import com.linkage.jz.bankruptcy.bean.AddrList;
import com.linkage.jz.bankruptcy.bean.ConfigInfo;
import com.linkage.jz.bankruptcy.bean.LoginInfo;
import com.linkage.jz.bankruptcy.bean.TokenInfo;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.fragment.MainFragment;
import com.linkage.jz.bankruptcy.fragment.MsgFragment;
import com.linkage.jz.bankruptcy.fragment.Project.ProjectFragment;
import com.linkage.jz.bankruptcy.fragment.SettingFragment;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.push.GTPushService;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.SignUtil;
import com.linkage.jz.bankruptcy.widget.LoginNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PublicLoginNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.register.RegisterActivity;
import com.linkage.seapeak.pojo.QQAuthData;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class MainActivity extends FragmentActivity implements OnClickListener {
    //声明ViewPager
    private ViewPager mViewPager;
    private ShapeLoadingDialog shapeLoadingDialog;
    //适配器
    private FragmentPagerAdapter mAdapter;
    private String[] mPermissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private AlertDialog mDialog;
    //装载Fragment的集合
    private List<Fragment> mFragments;

    //四个Tab对应的布局
    private LinearLayout mTabWeixin;
    private LinearLayout mTabFrd;
    private LinearLayout mTabAddress;
    private LinearLayout mTabSetting;

    //四个Tab对应的ImageButton
    private ImageButton mImgWeixin;
    private ImageButton mImgFrd;
    private ImageButton mImgAddress;
    private ImageButton mImgSetting;
    private TextView mTvMainTop;
    private RelativeLayout main_top_ll;
    private TextView mHomeTv, mProjectsTv, mMsgtv, mPerson_tv, mMain_allread;


    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        requestPermission();
        initViews();//初始化控件
        initEvents();//初始化事件
        initDatas();//初始化数据
//
        getToken();

        setTimer();
        Window window = getWindow();
        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

        //设置状态栏字体颜色为黑色
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        window.setStatusBarColor(getResources().getColor(R.color.page_top));
        //设置状态栏字体颜色为白色
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
//        shapeLoadingDialog = new ShapeLoadingDialog(this);


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
//        selectTab(0);
    }

    private void setTimer(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag){
                    try {
                        Thread.sleep(1*60*1000); //休眠
                        mHanler.sendEmptyMessage(TIMER);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private static final int TIMER = 999;
    private static boolean flag = true;

    private Handler mHanler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case TIMER:
                    //去执行定时操作逻辑
                    getToken();
                    break;
                default:
                    break;
            }
        }
    };

    private void stopTimer(){
        flag = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在界面销毁的地方要解绑
        EventBus.getDefault().unregister(this);
        stopTimer();
    }

    private void initDatas() {
        mFragments = new ArrayList<>();
        //将四个Fragment加入集合中
        mFragments.add(new MainFragment());
        mFragments.add(new ProjectFragment());
        mFragments.add(new MsgFragment());
        mFragments.add(new SettingFragment());

        mImgWeixin.setImageResource(R.drawable.tab_home_press);

        mHomeTv.setTextColor(getResources().getColor(R.color.page_top));
        mPerson_tv.setTextColor(getResources().getColor(R.color.text_secondary_color));
        mMsgtv.setTextColor(getResources().getColor(R.color.text_secondary_color));
        mProjectsTv.setTextColor(getResources().getColor(R.color.text_secondary_color));

        //初始化适配器
        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {//从集合中获取对应位置的Fragment
                return mFragments.get(position);
            }

            @Override
            public int getCount() {//获取集合中Fragment的总数
                return mFragments.size();
            }

        };
        //不要忘记设置ViewPager的适配器
        mViewPager.setAdapter(mAdapter);
        //设置ViewPager的切换监听
        mViewPager.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            //页面滚动事件
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            //页面选中事件
            @Override
            public void onPageSelected(int position) {
                //设置position对应的集合中的Fragment
                mViewPager.setCurrentItem(position);
                resetImgs();
                selectTab(position);
            }

            @Override
            //页面滚动状态改变事件
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initEvents() {
        //设置四个Tab的点击事件
        mTabWeixin.setOnClickListener(this);
        mTabFrd.setOnClickListener(this);
        mTabAddress.setOnClickListener(this);
        mTabSetting.setOnClickListener(this);

    }

    //初始化控件
    private void initViews() {
        mTvMainTop = (TextView) findViewById(R.id.main_top);
        mHomeTv = (TextView) findViewById(R.id.id_tab_home_tv);
        mProjectsTv = (TextView) findViewById(R.id.id_tab_projects_tv);
        mPerson_tv = (TextView) findViewById(R.id.id_tab_person_tv);
        mMsgtv = (TextView) findViewById(R.id.id_tab_msg_tv);
        mMain_allread = (TextView) findViewById(R.id.main_allread);
        mMain_allread.setTag(false);
        mMain_allread.setVisibility(View.GONE);

        mMain_allread.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
//                UnReadAll();
                EventBus.getDefault().post(new MsgFragment.ClearUnread());
            }
        });

        main_top_ll = (RelativeLayout) findViewById(R.id.main_top_ll);
//        rl_top= (RelativeLayout) findViewById(R.id.rl_top);
        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);

        mTabWeixin = (LinearLayout) findViewById(R.id.id_tab_weixin);
        mTabFrd = (LinearLayout) findViewById(R.id.id_tab_frd);
        mTabAddress = (LinearLayout) findViewById(R.id.id_tab_address);
        mTabSetting = (LinearLayout) findViewById(R.id.id_tab_setting);

        mImgWeixin = (ImageButton) findViewById(R.id.id_tab_weixin_img);
        mImgFrd = (ImageButton) findViewById(R.id.id_tab_frd_img);
        mImgAddress = (ImageButton) findViewById(R.id.id_tab_address_img);
        mImgSetting = (ImageButton) findViewById(R.id.id_tab_setting_img);
        EventBus.getDefault().register(this);

        mViewPager.setOffscreenPageLimit(7);
    }

    @Subscribe
    public void getEventBus(ShowHideClearAll clearAll) {
        mMain_allread.setTag(clearAll.isShow);
        if (mTvMainTop.getText().toString().equals("消息中心"))
            mMain_allread.setVisibility(clearAll.isShow ? View.VISIBLE : View.GONE);
    }

    /**
     * 为了防止混淆更新消息的EventBus与其他管道重合
     */
    public static class ShowHideClearAll {
        public boolean isShow;

        public ShowHideClearAll(boolean isShow) {
            this.isShow = isShow;
        }
    }

    @Override
    public void onClick(View v) {
        //先将四个ImageButton置为灰色
        resetImgs();

        //根据点击的Tab切换不同的页面及设置对应的ImageButton为绿色
        switch (v.getId()) {
            case R.id.id_tab_weixin:
                selectTab(0);
                break;
            case R.id.id_tab_frd:
                selectTab(1);
                break;
            case R.id.id_tab_address:
                selectTab(2);
                break;
            case R.id.id_tab_setting:
                selectTab(3);
                break;
        }
    }
    private PublicNoticeDialog noticeDialog;
    private void selectTab(int i) {
        Window window = getWindow();
        //根据点击的Tab设置对应的ImageButton为绿色
        switch (i) {
            case 0:
                mImgWeixin.setImageResource(R.drawable.tab_home_press);
                main_top_ll.setBackgroundColor(getResources().getColor(R.color.page_top));
                mTvMainTop.setText("破晓");
                mTvMainTop.setTextColor(getResources().getColor(R.color.white));
                mHomeTv.setTextColor(getResources().getColor(R.color.page_top));
                mMain_allread.setVisibility(View.GONE);
                main_top_ll.setVisibility(View.VISIBLE);
//                rl_top.setVisibility(View.GONE);



                //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

                //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

                //设置状态栏字体颜色为黑色
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

                window.setStatusBarColor(getResources().getColor(R.color.page_top));
                //设置状态栏字体颜色为白色
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);



                break;
            case 1:
                mImgFrd.setImageResource(R.drawable.tab_projects_press);

                main_top_ll.setBackgroundColor(getResources().getColor(R.color.white));
                mTvMainTop.setText("项目");
                mTvMainTop.setTextColor(getResources().getColor(R.color.page_top));
                mProjectsTv.setTextColor(getResources().getColor(R.color.page_top));
                mMain_allread.setVisibility(View.GONE);
                main_top_ll.setVisibility(View.GONE);
//                Window window = getWindow();

                //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

                //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(getResources().getColor(R.color.white));
                //设置状态栏字体颜色为黑色
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);


                //设置状态栏字体颜色为白色
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

//                rl_top.setVisibility(View.VISIBLE);
                break;
            case 2:

                String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
                if ("".equalsIgnoreCase(userToken)) {
                    noticeDialog = new PublicNoticeDialog(MainActivity.this, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            switch (view.getId()) {
                                case R.id.ll_close:
                                    noticeDialog.dismiss();
                                    break;

                                case R.id.btn_chancel_notice:
                                    noticeDialog.dismiss();

                                    break;

                                case R.id.btn_save_notice:
                                    RegisterActivity.start(MainActivity.this);
                                    noticeDialog.dismiss();
                                    break;

                            }

                        }
                    }, 1, "提示", "操作此功能，需要请您先注册/登录",
                            "取消", "确认");
                    noticeDialog.show();
                    return;
                }
                mImgAddress.setImageResource(R.drawable.tab_message_press);
                main_top_ll.setBackgroundColor(getResources().getColor(R.color.white));
                mTvMainTop.setText("消息中心");
                mTvMainTop.setTextColor(getResources().getColor(R.color.page_top));
                mMsgtv.setTextColor(getResources().getColor(R.color.black));
                mMain_allread.setVisibility(((boolean) mMain_allread.getTag()) ? View.VISIBLE : View.GONE);
                main_top_ll.setVisibility(View.VISIBLE);
//                rl_top.setVisibility(View.GONE);
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

                //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

                window.setStatusBarColor(getResources().getColor(R.color.white));
                //设置状态栏字体颜色为黑色
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);


                //设置状态栏字体颜色为白色
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                break;
            case 3:
                mImgSetting.setImageResource(R.drawable.tab_personal_press);
                main_top_ll.setBackgroundColor(getResources().getColor(R.color.white));
                mTvMainTop.setText("设置");
                mTvMainTop.setTextColor(getResources().getColor(R.color.page_top));
                mPerson_tv.setTextColor(getResources().getColor(R.color.page_top));
                mMain_allread.setVisibility(View.GONE);
                main_top_ll.setVisibility(View.GONE);
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

                //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

                window.setStatusBarColor(getResources().getColor(R.color.white));
                //设置状态栏字体颜色为黑色
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);


                //设置状态栏字体颜色为白色
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//                rl_top.setVisibility(View.GONE);
                break;
        }
        //设置当前点击的Tab所对应的页面
        mViewPager.setCurrentItem(i);
    }

    //将四个ImageButton设置为灰色
    private void resetImgs() {
        mImgWeixin.setImageResource(R.drawable.tab_home);
        mImgFrd.setImageResource(R.drawable.tab_projects);
        mImgAddress.setImageResource(R.drawable.tab_message);
        mImgSetting.setImageResource(R.drawable.tab_personal);

        mHomeTv.setTextColor(getResources().getColor(R.color.text_secondary_color));
        mPerson_tv.setTextColor(getResources().getColor(R.color.text_secondary_color));
        mMsgtv.setTextColor(getResources().getColor(R.color.text_secondary_color));
        mProjectsTv.setTextColor(getResources().getColor(R.color.text_secondary_color));
    }

    public void getToken() {

        OkHttpClient okHttpClient = new OkHttpClient();
        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = Math.abs(random.nextLong()) + "";
        String timestamp = System.currentTimeMillis() + "";
        params.put("appid", Consts.APPID);
        params.put("nonce", rom);
        params.put("timestamp", timestamp);

        String sign = SignUtil.createSign(Consts.APPKEY, params);

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("sign", sign)
                .build();

        String url = Consts.WEBURL_GETTOKEN;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
//                String str = "";
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();


                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        Gson gson = new Gson();
                        TokenInfo info = gson.fromJson(object.optString("data"), TokenInfo.class);
                        BankruptcyApp.tokeninfo = info;
                        SPUtils.getInstance(Consts.SPNAME).put("tokeninfo", object.optString("data"));
//                        String saveCid = SPUtils.getInstance(Consts.SPNAME).getString("saveCid", "");
//                        if ("".equalsIgnoreCase(saveCid)) {
                        saveCid();
//                        }
                        getBanner("banner");
                        getBanner_start("starting");
                        getUserInfo();
                        getConfigList();
                        getAllAreaData();

                    }

                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public void saveCid() {
        String saveCid = SPUtils.getInstance(Consts.SPNAME).getString(GTPushService.CID_TAG, "");
        GTPushService.saveCid(MainActivity.this, saveCid);

//        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
//            getToken();
//            return;
//        }
//        TelephonyManager phone;
//        phone = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//
//        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
//        Random random = new Random();
//        String rom = random.nextLong() + "";
//        String timestamp = System.currentTimeMillis() + "";
//
//
//        String sign = SignUtil.createSign(Consts.APPKEY, params);
//
//        RequestBody requestBody = new FormBody.Builder()
//                .add("appid", "1000000001")
//                .add("nonce", rom)
//                .add("timestamp", timestamp)
//                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("appVersion", "0.0.1")
//                .add("cid", "1000000001")
//                .add("os", "0")
//                .add("osVersion", Build.VERSION.SDK)
//                .add("model", android.os.Build.MODEL)
//                .add("manufacturer", android.os.Build.MANUFACTURER)
//                .build();
//
//        String url = Consts.WEBURL_SAVECID;
//        Request request = new Request.Builder()
//                .url(url)
//                .post(requestBody)
//                .build();
//
//        okHttpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
////                Log.d(TAG, "onFailure: " + e.getMessage());
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
////                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
//                Headers headers = response.headers();
//
//
//                String str = response.body().string();
//                try {
//                    JSONObject object = new JSONObject(str);
//                    if (object.optInt("code") == 0) {
//                        Gson gson = new Gson();
//                        JSONObject data = object.getJSONObject("data");
//                        String cid = data.optString("appInfoId");
//                        SPUtils.getInstance(Consts.SPNAME).put("saveCid", cid);
//                    }
//
//                    str = "";
//                } catch (Exception ex) {
//                    ex.printStackTrace();
//                }
//            }
//        });
    }



    public void getBanner(final String type) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken();
            return;
        }

        TelephonyManager phone;
        phone = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        OkHttpClient okHttpClient = new OkHttpClient();
        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";


        String sign = SignUtil.createSign(Consts.APPKEY, params);

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("code", type)
                .build();

        String url = Consts.WEBURL_BANNER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                int i = 0;
                Log.d("", "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();


                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        Gson gson = new Gson();
                        JSONArray data = object.getJSONArray("data");
//                        String baseUrl = data.optString("baseUrl");
//                        String links = data.optString("links");
                        if ("starting".equalsIgnoreCase(type)) {
                            SPUtils.getInstance(Consts.SPNAME).put("startbaseUrl", "");
                            SPUtils.getInstance(Consts.SPNAME).put("startlinks", data.toString());
                        }
                        if ("banner".equalsIgnoreCase(type)) {
                            SPUtils.getInstance(Consts.SPNAME).put("bannerbaseUrl", "");
                            SPUtils.getInstance(Consts.SPNAME).put("bannerlinks", data.toString());
                        }


//                        BankruptcyApp.tokeninfo = info;
//                        String saveCid = SPUtils.getInstance(Consts.SPNAME).getString("saveCid","");
//                        if("".equalsIgnoreCase(saveCid))
//                        {
//                        SPUtils.getInstance(Consts.SPNAME).put("saveCid",cid);
//                        }
                    }

                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });


    }

    public void getBanner_start(final String type) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken();
            return;
        }

        TelephonyManager phone;
        phone = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        OkHttpClient okHttpClient = new OkHttpClient();
        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";


        String sign = SignUtil.createSign(Consts.APPKEY, params);

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("code", type)
                .build();

        String url = Consts.WEBURL_BANNER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                int i = 0;
//                Log.d(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();


                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        Gson gson = new Gson();
                        JSONArray data = object.getJSONArray("data");
//                        String baseUrl = data.optString("baseUrl");
//                        String links = data.optString("links");
                        if ("starting".equalsIgnoreCase(type)) {
                            SPUtils.getInstance(Consts.SPNAME).put("startbaseUrl", "");
                            SPUtils.getInstance(Consts.SPNAME).put("startlinks", data.toString());
                        }
                        if ("banner".equalsIgnoreCase(type)) {
                            SPUtils.getInstance(Consts.SPNAME).put("bannerbaseUrl", "");
                            SPUtils.getInstance(Consts.SPNAME).put("bannerlinks", data.toString());
                        }
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                EventBus.getDefault().post(Consts.EVENTSHOWTOPIMG);

                            }

                        });

//                        BankruptcyApp.tokeninfo = info;
//                        String saveCid = SPUtils.getInstance(Consts.SPNAME).getString("saveCid","");
//                        if("".equalsIgnoreCase(saveCid))
//                        {
//                        SPUtils.getInstance(Consts.SPNAME).put("saveCid",cid);
//                        }
                    }

                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });


    }

    private PublicLoginNoticeDialog publicLoginNoticeDialog;

    public void getUserInfo() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken();
            return;
        }
        final String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        if ("".equalsIgnoreCase(userToken)) {
            return;
        }

        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String saveCid = SPUtils.getInstance(Consts.SPNAME).getString("saveCid", "");
        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
//                .add("mobile", mobile)
                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("password", pwd)
//                .add("smsCaptcha", code)
//                .add("appInfoId", saveCid)
                .add("userToken", userToken)
                .build();

        String url = Consts.WEBURL_GETUSERINFO;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {


                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if  (object.optInt("code") == -10004 || (object.optInt("code") == -10003))
                    {

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                LoginNoticeDialog.showPage(object.optString("msg"));
                            }

                        });

                        return;
                    }
                        if (object.optInt("code") == 0) {
                        Gson gson = new Gson();
                        JSONObject data = object.getJSONObject("data");

                        SPUtils.getInstance(Consts.SPNAME).put("userInfo", data.toString());
                        LoginInfo info = gson.fromJson(data.optString("userInfo"), LoginInfo.class);
                        SPUtils.getInstance(Consts.SPNAME).put("userId", info.getId());
                        BankruptcyApp.loginInfo = info;
                        BankruptcyApp.userToken = userToken;
//                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
//                                Toast.makeText(MainActivity.this,"登录失败",Toast.LENGTH_SHORT).show();

                            }

                        });
//                        finish();
                    }

                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }


    private void getConfigList() {

        Observable<JsonObject> observable = null;
        observable = Network
                .getAPIService()
                .getConfigList("");


        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {

                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonArray arr = json.getAsJsonArray("data");
                        List<ConfigInfo> list = ConfigInfo.parse(arr);

                        for(int i=0;i<list.size();i++) {
                            ConfigInfo info = list.get(i);
                            SPUtils.getInstance(Consts.SPNAME).put(info.getCode(), info.getName());
                        }


                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {

                        super.onError(e);
                    }
                });

    }



    private void requestPermission() {
        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            // 检查该权限是否已经获取
            int i = checkSelfPermission(mPermissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (i != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                showDialogTipUserRequestPermission();
            }


        }
    }

    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {

        new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("由于需要获取存储空间，为你存储个人信息；\n否则，您将无法正常使用")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.M)
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        requestPermissions(mPermissions, 321);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }


    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else
                        finish();
                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    // 提示用户去应用设置界面手动开启权限

    private void showDialogTipUserGoToAppSettting() {

        mDialog = new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("请在-应用设置-权限-中，允许APM使用存储权限来保存用户数据")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }


//    private PublicNoticeDialog noticeDialog;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            exit();
//            return false;

            noticeDialog = new PublicNoticeDialog(MainActivity.this,onClickListener,
                    1,"提示","确认退出程序吗？",
                    "取消","确认");
            noticeDialog.show();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_MY_PRO) ||TextUtils.equals(event.getType(), RefreshEvent.TYPE_PU_PRO)) {
            selectTab(1);
        } else if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_MESSAGE)){
            selectTab(2);
        }
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.ll_close:
                    noticeDialog.dismiss();
                    break;

                case R.id.btn_chancel_notice:
//                   Boolean flag =  noticelxDialog.cb_agree.isChecked();
                    noticeDialog.dismiss();
                    break;

                case R.id.btn_save_notice:
                    finish();
                    noticeDialog.dismiss();
                    break;

            }
        }
    };


    public void getAllAreaData()
    {
        Observable<JsonObject> observable;

        observable = Network
                .getAPIService()
                .getAllAreaData( "");


        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {

                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject objdata = json.getAsJsonObject("data");
                        AddrList data = new Gson().fromJson(objdata.toString(), AddrList.class);
                        int i = 0;

                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {

                        super.onError(e);
                    }
                });
    }
}
